import React, { useEffect, useState } from 'react'
import './index.scss'
import {
  Input, DatePicker, Select, Table, Pagination,
  Space, Button, Modal, message, Form
} from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { orderDetail, orderEdit, orderList } from '../../api/order';
import dayjs from 'dayjs';
const { RangePicker } = DatePicker
const { Option } = Select;

export default function Orders() {

  const columns = [
    {
      title: '订单号',   //表格标题
      dataIndex: 'orderId',    //列数据在数据项中对应的路径
    },
    {
      title: '下单时间',
      dataIndex: 'orderTime',
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
    },
    {
      title: '收货人',
      dataIndex: 'consignee',
    },
    {
      title: '送货地址',
      dataIndex: 'address',
    },
    {
      title: '送达时间',
      dataIndex: 'deliveryTime',
    },
    {
      title: '备注',
      dataIndex: 'remark',
    },
    {
      title: '订单金额',
      dataIndex: 'amount',
    },
    {
      title: '订单状态',
      dataIndex: 'status',
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => showDetailModal(record)}>查看</a>
          <a onClick={() => showEditModal(record)}>编辑</a>
        </Space>)
    }
  ];
  const layout = {
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 16,
    },
  };
  const [form] = Form.useForm()

  const [currentPage, setCurrentPage] = useState(1) //初始打开的页数
  const [pageSize, setPageSize] = useState(5) //每页数据初始条数
  const [data, setData] = useState([]) //初始数据
  const [total, setTotal] = useState() //总条数
  const [searchOrderNo, setSearchOrderNo] = useState()
  const [searchConsignee, setSearchConsignee] = useState()
  const [searchPhone, setSearchPhone] = useState()
  const [searchOrderState, setSearchOrderState] = useState()
  const [date, setDate] = useState([])
  // 获取订单列表
  const orderData = async (value) => {
    const res = await orderList(value) //当前每页条数所拿到接口的数据
    setTotal(res.data.total) //将接口的数据总条数赋给total
    const goods = res.data.data;//把拿到接口的数据赋给goods
    const newData = goods.map(item => ({
      key: item.id,
      orderId: item.orderNo,
      deliveryTime: dayjs(item.deliveryTime).format('YYYY-MM-DD HH:mm:ss'),
      phone: item.phone,
      consignee: item.consignee,
      address: item.deliverAddress,
      orderTime: dayjs(item.orderTime).format('YYYY-MM-DD HH:mm:ss'),
      remark: item.remarks,
      amount: item.orderAmount,
      status: item.orderState
    }))
    setData(newData)
  }
  // 修改页
  const onPageChange = (page, pageSize) => {
    setCurrentPage(page);
    setPageSize(pageSize);
  };
  // 搜索
  const handleChange = () => {
    const data = {
      currentPage,
      pageSize,
      orderNo: searchOrderNo,
      consignee: searchConsignee,
      phone: searchPhone,
      orderState: searchOrderState,
      date: date
    }
    orderData(data)
  };
  // 获取时间
  const searchTime = (e) => {
    if (e) {
      const jsonString = JSON.stringify(e.map(item => dayjs(item.$d).format('YY-MM-DD HH:mm:ss')))
      setDate(jsonString)
    }
  }

  // 对话框
  // 查看订单对话框状态
  const [detailModalOpen, setDetailModalOpen] = useState(false);
  // 修改订单对话框状态
  const [editModalOpen, setEditModalOpen] = useState(false);
  const [nowData, setNowData] = useState({
    id: '',
    orderNo: '',
    orderTime: '',
    phone: '',
    consignee: '',
    deliverAddress: '',
    deliveryTime: '',
    remarks: '',
    orderAmount: '',
    orderState: ''
  })
  // 订单详情
  const detail = async (value) => {
    const res = await orderDetail(value)
    console.log(res);
    const data = res.data.data
    setNowData({
      id: data.id,
      orderNo: data.orderNo,
      orderTime: data.orderTime,
      phone: data.phone,
      consignee: data.consignee,
      deliverAddress: data.deliverAddress,
      deliveryTime: data.deliveryTime,
      remarks: data.remarks,
      orderAmount: data.orderAmount,
      orderState: data.orderState
    })
  }
  // 订单详情对话框
  const showDetailModal = (value) => {
    setDetailModalOpen(true);
    const id = value.key
    detail({ id })
  };
  // 关闭对话框
  const detailCancel = () => {
    setDetailModalOpen(false);
  };

  // 修改订单
  const edit = async (value) => {
    console.log(value);
    const res = await orderEdit(value)
    console.log(res);
    const { code, msg } = res.data
    if (code == 0) {
      message.open({
        type: 'success',
        content: msg
      })
    }
  }
  // 修改订单对话框
  const [detailId, setDetailId] = useState()
  const showEditModal = async (value) => {
    const id = value.key
    setDetailId(id)
    const res = await orderDetail({ id })
    const data = res.data.data
    form.setFieldsValue({
      orderNo: data.orderNo,
      orderTime: dayjs(data.orderTime),
      phone: data.phone,
      consignee: data.consignee,
      deliverAddress: data.deliverAddress,
      deliveryTime: dayjs(data.deliveryTime),
      remarks: data.remarks,
      orderAmount: data.orderAmount,
      orderState: data.orderState
    })
    setEditModalOpen(true);
  }
  const editOk = () => {
    const formData = form.getFieldsValue()
    const { orderNo, orderTime, phone, consignee, deliverAddress, deliveryTime, remarks, orderAmount, orderState } = formData
    const data = {
      id: detailId,
      orderNo: orderNo,
      orderTime: dayjs(orderTime).format('YYYY-MM-DD HH:mm:ss'),
      phone: phone,
      consignee: consignee,
      deliverAddress: deliverAddress,
      deliveryTime: dayjs(deliveryTime).format('YYYY-MM-DD HH:mm:ss'),
      remarks: remarks,
      orderAmount: orderAmount,
      orderState: orderState
    }
    edit(data)
    orderData({ currentPage, pageSize })
    setEditModalOpen(false);
  };
  const editCancel = () => {
    setEditModalOpen(false);
  };

  useEffect(() => {
    orderData({ currentPage, pageSize })
  }, [currentPage, pageSize])

  return (
    <>
      <div className="order-inp">
        <div className="input">
          <span className='text'>订单号</span>
          <Input placeholder="请输入订单号" className='inp' onChange={(e) => setSearchOrderNo(e.target.value)} />
        </div>
        <div className="input">
          <span className='text'>收货人</span>
          <Input placeholder="请输入收货人" className='inp' onChange={(e) => setSearchConsignee(e.target.value)} />
        </div>
        <div className="input">
          <span className='text'>手机号</span>
          <Input placeholder="请输入手机号" className='inp' onChange={(e) => setSearchPhone(e.target.value)} />
        </div>
        <div className="input">
          <span className='text'>订单状态</span>
          <Select
            defaultValue="请选择订单状态"
            className='inp'
            onChange={(e) => setSearchOrderState(e)}
            options={[
              { value: '已受理', label: '已受理' },
              { value: '派送中', label: '派送中' },
              { value: '已完成', label: '已完成' }
            ]}
          />
        </div>
        <div className="input-date">
          <span className='text'>选择时间</span>
          <RangePicker showTime className='date' onChange={searchTime} />
        </div>
        <Button type="primary" icon={<SearchOutlined />} onClick={handleChange}>
          搜索
        </Button>

      </div>

      <div className="order-list">
        <Table dataSource={data} columns={columns} pagination={false} />
      </div>

      <Modal
        title='订单详情'
        open={detailModalOpen}
        onCancel={detailCancel}
        footer={null}
      >
        <p>订单ID:{nowData.id}</p>
        <p>订单号:{nowData.orderNo}</p>
        <p>下单时间:{nowData.orderTime}</p>
        <p>联系电话:{nowData.phone}</p>
        <p>收货人:{nowData.consignee}</p>
        <p>送货地址:{nowData.deliverAddress}</p>
        <p>送达时间:{nowData.deliveryTime}</p>
        <p>备注:{nowData.remarks}</p>
        <p>订单金额:{nowData.orderAmount}</p>
        <p>订单状态:{nowData.orderState}</p>
      </Modal>

      <Modal
        title='修改订单'
        open={editModalOpen}
        onOk={editOk}
        onCancel={editCancel}
      >
        <Form
          {...layout}
          form={form}
          name="control-hooks"
          style={{
            maxWidth: 600,
          }}
        >
          <Form.Item
            label="订单号"
            name="orderNo"

          >
            <Input style={{ width: '190px', marginRight: '20px' }} />
          </Form.Item>
          <Form.Item
            label="下单时间"
            name="orderTime"
          >
            <DatePicker
              showTime
            />
          </Form.Item>

          <Form.Item
            label="手机号"
            name="phone"
          >
            <Input style={{ width: '190px', marginRight: '20px' }} />
          </Form.Item>

          <Form.Item
            label="收货人"
            name="consignee"
          >
            <Input style={{ width: '190px', marginRight: '20px' }} />
          </Form.Item>

          <Form.Item
            label="送货地址"
            name="deliverAddress"
          >
            <Input style={{ width: '190px', marginRight: '20px' }} />
          </Form.Item>

          <Form.Item
            label="送达时间"
            name="deliveryTime"
          >
            <DatePicker
              showTime
            />
          </Form.Item>

          <Form.Item
            label="备注"
            name="remarks"
          >
            <Input style={{ width: '190px', marginRight: '20px' }} />
          </Form.Item>

          <Form.Item
            label="订单金额"
            name="orderAmount"
          >
            <Input style={{ width: '190px', marginRight: '20px' }} />
          </Form.Item>

          <Form.Item
            label="订单状态"
            name="orderState"
          >
            <Select
              allowClear
            >
              <Option value="已受理">已受理</Option>
              <Option value="派送中">派送中</Option>
              <Option value="已完成">已完成</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      <div className="order-page">
        <Pagination
          total={total}
          defaultPageSize={pageSize}
          pageSizeOptions={[5, 10, 20, 30]}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => `共 ${total} 条`}
          onChange={onPageChange}
        />
      </div>
    </>
  )
}
